<#
	#   It is recommended to test the script on a local machine for its purpose and effects. 
	#   Endpoint Central will not be responsible for any 
	#   damage/loss to the data/setup based on the behavior of the script.

	#   Description: Script to create a new VPN connection without credentials

	#   Configuration Type - COMPUTER

	#	Arguments 
		"VPNName" "ServerAddress" "ConnectionType" "TunnelType"	
		
	#	EXAMPLE
		"My VPN" "vpn.example.com" "IKEv2" "L2tp"
		
	#	Note:
		The VPN connection will be added, but it will not validate the VPN credentials. The end user needs to configure it manually.
#>

# Check if the minimum number of arguments for adding a VPN is provided
if ($args.Length -lt 4) {
    Write-Host "Usage: .\ScriptName.ps1 'VPNName' 'ServerAddress' 'ConnectionType' 'TunnelType' ['Username' 'Password']"
    Write-Host "Username and Password are optional for adding a VPN"
    exit
}

# Parse arguments
$VPNName = $args[0]
$ServerAddress = $args[1]
$ConnectionType = $args[2]
$TunnelType = $args[3]
$Username = $null
$Password = $null

# Check if username and password are provided
if ($args.Length -eq 6) {
    $Username = $args[4]
    $Password = $args[5]
}

# Function to add a VPN connection
function Add-VPN {
    param($Name, $Address, $ConType, $TunType, $User, $Pass)
    
    Add-VpnConnection -Name $Name -ServerAddress $Address -TunnelType $TunType -EncryptionLevel Optional -AuthenticationMethod MSChapv2 -SplitTunneling -AllUserConnection -Force -RememberCredential

    # If username and password are provided, use them to connect
    if ($User -and $Pass) {
        $cmd = "rasdial `"$Name`" `"$User`" `"$Pass`""
        Invoke-Expression -Command $cmd
        Write-Host "VPN connection added with credentials: $Name"
    } else {
        Write-Host "VPN connection added: $Name"
    }
}

# Try to add the VPN connection
try {
    Add-VPN -Name $VPNName -Address $ServerAddress -ConType $ConnectionType -TunType $TunnelType -User $Username -Pass $Password
} catch {
    Write-Host "An error occurred: $_"
}